package org.example.sample2.dao;

import lombok.Getter;
import lombok.Setter;
import org.example.sample2.api.CouponStrategy;
import org.example.sample2.imp.UseCouponStrategy;

import java.math.BigDecimal;
import java.util.HashMap;

@Setter
@Getter
public class Customer {

    private CouponStrategy couponStrategy;
    Integer id;
    String name;
    Coupon coupon;
    HashMap<String, FruitPack> bucket;

    public Integer add2Bucket(String fruitName,BigDecimal num, Supermarket supermarket) {
        if (fruitName == null) {
            return 0;
        }
        if (num.compareTo(new BigDecimal(0))<=0){
            return 0;
        }

        FruitPack storageChange = supermarket.storageOut(this,fruitName,num);
        if (storageChange == null) {
            return 1;
        }

        FruitPack fruitInBucket = bucket.get(fruitName);
        if (fruitInBucket == null) {
            storageChange.setMarketName(supermarket.getName());
            bucket.put(fruitName, storageChange);
        }else {
            fruitInBucket.setNum(fruitInBucket.getNum().add(storageChange.getNum()));
            bucket.put(fruitName, fruitInBucket);
        }
        return 2;
    }

    public Customer(Integer id, String name, Coupon coupon) {
        this.id = id;
        this.name = name;
        this.coupon = coupon;
        this.bucket = new HashMap<>();
        this.couponStrategy = new UseCouponStrategy();
    }

    public BigDecimal purchase(Supermarket supermarket) {
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (FruitPack fruitPack : bucket.values()) {
            if (fruitPack==null){
                continue;
            }
            if (fruitPack.getMarketName().equals(supermarket.getName())){
                if (fruitPack.getPrice().compareTo(BigDecimal.ZERO)>=0&fruitPack.getNum().compareTo(BigDecimal.ZERO)>=0){
                    totalPrice = totalPrice.add(fruitPack.getNum().multiply(fruitPack.getPrice()).multiply(fruitPack.getDiscount()).divide(new BigDecimal(100)));
                }
            }
        }
        totalPrice = this.couponStrategy.calculateTotal(this.coupon,totalPrice);
        return totalPrice;
    };

}
